.PHONY: start stop restart killclean info

EXE=AVAgent

# 启动服务
start:
	@echo "Starting AVAgent service..."
	@if [ -f AVAgent.pid ]; then \
		PID=$$(cat AVAgent.pid); \
		if ps -p $$PID > /dev/null; then \
			echo "Service is already running (PID: $$PID)"; \
			exit 0; \
		else \
			echo "Found stale PID file. Removing..."; \
			rm -f AVAgent.pid; \
		fi; \
	fi;\
	./$(EXE) && echo "Service started successfully"

# 停止服务
stop:
	@echo "Stopping AVAgent service..."
	@if [ ! -f AVAgent.pid ]; then \
		echo "PID file not found. Service may not be running"; \
		exit 0; \
	fi;\
	PID=$$(cat AVAgent.pid); \
	echo "Found PID: $$PID"; \
	if ps -p $$PID > /dev/null; then \
		echo "Sending SIGTERM to process $$PID"; \
		kill $$PID; \
#		sleep 1; \
		if ps -p $$PID > /dev/null; then \
			echo "Process still running, sending SIGKILL"; \
			kill -9 $$PID; \
		fi; \
	else \
		echo "Process $$PID not running"; \
	fi; \
	rm -f AVAgent.pid AVAgentDaemon.log AVAgentUser; \
	echo "Service stopped successfully"


# 强制清理（用于异常情况）
killclean:
	@echo "Performing force clean..."
	@pkill -f "./$(EXE)" || true
	@rm -f AVAgent.pid AVAgentDaemon.log AVAgentUser
	@echo "Force clean completed"

# 重启服务 - 先停止再启动
restart: stop start

# 显示服务状态和当前用户
info:
	@if [ -f AVAgent.pid ]; then \
		PID=$$(cat AVAgent.pid); \
		if ps -p $$PID > /dev/null; then \
			echo "Service is running (PID: $$PID)"; \
			if [ -f AVAgentUser ]; then \
				USER=$$(cat AVAgentUser); \
				echo "Current user: $$USER"; \
			else \
				echo "AVAgentUser file not found"; \
			fi; \
		else \
			echo "Found stale PID file. Service not running."; \
		fi; \
	else \
		echo "Service is not running (PID file not found)"; \
	fi

